package com.hmall.user.inteceptor;

import com.hmall.common.thread.User;
import com.hmall.common.thread.UserThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一个自定义的springmvc的拦截器
 * 目的
 *  从请求头对象中获取用户信息
 *  然后把用户信息保存到ThreadLocal当前线程中
 *
 */
public class MyHandleInteceptor implements HandlerInterceptor {
    /**
     * 在执行具体的请求路径之前执行
     * @param request  请求对象
     * @param response  响应对象
     * @param handler
     * @return  true表示放行，false表示拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头对象中获取用户信息
        String userId = request.getHeader("authorization");

        //2.保存到ThreadLocal中
        User user=new User();
        user.setId(Long.parseLong(userId));
        UserThreadLocal.setUser(user);

        //3.放行
        return true;
    }

    /**
     * 在执行具体的请求路径之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //删除threadlocal中的信息，防止OOM
        UserThreadLocal.delUser();
    }
}
